﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;

using System.Xml.Linq;
using ESRI.ArcGIS.ADF.Connection.AGS;
using ESRI.ArcGIS.Server;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.ADF;

/// <summary>
/// Summary description for ConnectionHelper
/// </summary>
namespace EAGL.Server
{
    public class ConnectionManager : IDisposable
    {

        // connection parameters
        AGSServerConnection serverConnection;
        private ArcGISServerConnectionInfo connInfo;
        private IServerObjectManager som;
        private IServerObjectAdmin admin;




        public ConnectionManager(ArcGISServerConnectionInfo connInfo)
        {
            this.connInfo = connInfo;
            createNewConnection();
        }

        public ConnectionManager(string userName, string password, string host)
            : this(new ArcGISServerConnectionInfo(userName, password, host)) { }


        private void createNewConnection()
        {
            try
            {
                Identity ident = new Identity();
                ident.UserName = connInfo.UserName;
                ident.Password = connInfo.Password;
                serverConnection = new AGSServerConnection(connInfo.Host, ident);
                serverConnection.Connect();
                initServerObjects();
            }
            catch (Exception ex)
            {
                throw new Exception("Error in creating new connection: " + ex.Message);
            }
        }

        private void initServerObjects()
        {
            try
            {
                som = serverConnection.ServerObjectManager;
                admin = serverConnection.ServerObjectAdmin;
            }
            catch (Exception ex)
            {
                throw new Exception("Error while initializing one of the server objects: " + ex.Message);
            }
        }

        public AGSServerConnection GetConnectionInstance()
        {
            return serverConnection;
        }

        public bool IsConnected
        {
            get
            {
                return serverConnection != null ? serverConnection.IsConnected : false;
            }
        }

        public bool IsAlive
        {
            get
            {
                return serverConnection != null ? serverConnection.IsAlive() : false;
            }
        }

        public IServerObjectManager ObjectManager
        {
            get { return som; }
        }

        public IServerObjectAdmin ObjectAdmin
        {
            get { return admin; }
        }

        #region IDisposable Members

        public void Dispose()
        {
            if (serverConnection != null)
                serverConnection.Dispose();
        }

        #endregion
    }
}